﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Everynet.Models;
using System.Net;
using System.Collections.Specialized;
using System.Text;
using System.Security.Cryptography;
using System.Web.Helpers;
using System.IO;
using System.Configuration;
using System.Xml;
using System.Security.Cryptography.X509Certificates;
using System.Data.Odbc;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
using System.Data;
using System.Xml.Linq;
using System.Data.SqlClient;


namespace Everynet.Controllers
{
    public class testingController : Controller
    {
        private EverynetEntities db = new EverynetEntities();
        #region[Testing WHMCS]

       /* public enum QuotaMonths
        {
            OneMonth = 1,
            ThreeMonth = 3,
            SubYearly = 6,
            Yearly = 12
        }

        public enum QuotaMonthYear
        {
            months,
            year
        }
        public ActionResult WhmcsTestcustom()
        {
            string Mainusername = ConfigurationManager.AppSettings["WhmcsUsername"].ToString();
            string Mainpassword = ConfigurationManager.AppSettings["WhmcsPassword"].ToString();
            string path = ConfigurationManager.AppSettings["WhmcsPath"].ToString();

            // Instantiate the WebClient object
            WebClient WHMCSclient = new WebClient();
            #region[check custom function]
           
            //1. ProductConfig
            NameValueCollection formcustom = new NameValueCollection();
            formcustom.Add("username", Mainusername);
            formcustom.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
            formcustom.Add("action", "getproductconfiglinks");// action performed by the API:Functions
            Byte[] responseDataContact = WHMCSclient.UploadValues(path, formcustom);
            ViewBag.DisplayData = Encoding.ASCII.GetString(responseDataContact);
            string getXML = ViewBag.DisplayData;

            XmlDocument xd = new XmlDocument();
            xd.LoadXml(getXML);
            XmlNamespaceManager manager = new XmlNamespaceManager(xd.NameTable);

            String getCommaSeparatedGID = String.Empty;
            String getCommaSeparatedPID = String.Empty;

            string queryGID = "/whmcsapi/products/gid";
            XmlNodeList xnListGID = xd.SelectNodes(queryGID, manager);
            foreach (XmlNode xnGID in xnListGID)
            {
                getCommaSeparatedGID += xnGID.InnerText + "||";
            }

            string queryPID = "/whmcsapi/products/pid";
            XmlNodeList xnListPID = xd.SelectNodes(queryPID, manager);
            foreach (XmlNode xnPID in xnListPID)
            {
                getCommaSeparatedPID += xnPID.InnerText + "||";
            }



            //2.Quota Price
            NameValueCollection formcustomP = new NameValueCollection();
            formcustomP.Add("username", Mainusername);
            formcustomP.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
            formcustomP.Add("action", "getpriceforQuota");// action performed by the API:Functions
            Byte[] responseDataContactP = WHMCSclient.UploadValues(path, formcustomP);
            string getXMLP = Encoding.ASCII.GetString(responseDataContactP);


            XmlDocument xdP = new XmlDocument();
            xdP.LoadXml(getXMLP);
            XmlNamespaceManager managerP = new XmlNamespaceManager(xdP.NameTable);

            String getCommaSeparatedrelId= String.Empty;
            String getCommaSeparatedType = String.Empty;
            String getCommaSeparatedMsetupfee = String.Empty;
            String getCommaSeparatedQsetupfee = String.Empty;
            String getCommaSeparatedSsetupfee = String.Empty;

            string queryrel = "/whmcsapi/products/relid";
            XmlNodeList xnListrel = xdP.SelectNodes(queryrel, managerP);
            foreach (XmlNode xnrel in xnListrel)
            {
                getCommaSeparatedrelId += xnrel.InnerText + "||";
            }

            string querytype = "/whmcsapi/products/type";
            XmlNodeList xnListtype = xdP.SelectNodes(querytype, managerP);
            foreach (XmlNode xntype in xnListtype)
            {
                getCommaSeparatedType += xntype.InnerText + "||";
            }

            string queryMsetupfee = "/whmcsapi/products/msetupfee";
            XmlNodeList xnListM = xdP.SelectNodes(queryMsetupfee, managerP);
            foreach (XmlNode xnM in xnListM)
            {
                getCommaSeparatedMsetupfee += xnM.InnerText + "||";
            }

            string queryQsetupfee = "/whmcsapi/products/qsetupfee";
            XmlNodeList xnListQ = xdP.SelectNodes(queryQsetupfee, managerP);
            foreach (XmlNode xnQ in xnListQ)
            {
                getCommaSeparatedQsetupfee += xnQ.InnerText + "||";
            }

            string querySsetupfee = "/whmcsapi/products/ssetupfee";
            XmlNodeList xnListS = xdP.SelectNodes(querySsetupfee, managerP);
            foreach (XmlNode xnS in xnListS)
            {
                getCommaSeparatedSsetupfee += xnS.InnerText + "||";
            }

            //GetGidbyPid
            NameValueCollection formcustomG = new NameValueCollection();
            formcustomG.Add("username", Mainusername);
            formcustomG.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
            formcustomG.Add("action", "getGidbyPid");// action performed by the API:Functions
            Byte[] responseDataContactG = WHMCSclient.UploadValues(path, formcustomG);
            string getXMLG = Encoding.ASCII.GetString(responseDataContactG);

            XmlDocument xdG = new XmlDocument();
            xdG.LoadXml(getXMLG);
            XmlNamespaceManager managerG = new XmlNamespaceManager(xdG.NameTable);
           
            String getCommaSeparatedGGID = String.Empty;
            String getCommaSeparatedGPID = String.Empty;

            string queryG = "/whmcsapi/products/gid";
            XmlNodeList xnListG = xdG.SelectNodes(queryG, managerG);
            foreach (XmlNode xnG in xnListG)
            {
                getCommaSeparatedGGID += xnG.InnerText + "||";
            }

            string queryP = "/whmcsapi/products/id";
            XmlNodeList xnListP = xdG.SelectNodes(queryP, managerG);
            foreach (XmlNode xnP in xnListP)
            {
                getCommaSeparatedGPID += xnP.InnerText + "||";
            }


            string[] separator = new string[] { "||" };
            string[] strSplitArrGID = getCommaSeparatedGID.Split(separator, StringSplitOptions.None);
            string[] strSplitArrPID = getCommaSeparatedPID.Split(separator, StringSplitOptions.None);

            string[] strSplitArrrelID = getCommaSeparatedrelId.Split(separator, StringSplitOptions.None);
            string[] strSplitArrType = getCommaSeparatedType.Split(separator, StringSplitOptions.None);
            string[] strSplitArrM = getCommaSeparatedMsetupfee.Split(separator, StringSplitOptions.None);
            string[] strSplitArrQ = getCommaSeparatedQsetupfee.Split(separator, StringSplitOptions.None);
            string[] strSplitArrS = getCommaSeparatedSsetupfee.Split(separator, StringSplitOptions.None);

            string[] strSplitArrGGID = getCommaSeparatedGGID.Split(separator, StringSplitOptions.None);
            string[] strSplitArrGPID = getCommaSeparatedGPID.Split(separator, StringSplitOptions.None);

            for (int i = 0; i < strSplitArrGID.Length; i++)
            {
                if (!String.IsNullOrEmpty(strSplitArrPID[i]))
                    {
                        Int32 GID = Convert.ToInt32(strSplitArrGID[i]);
                        Int32 PID = Convert.ToInt32(strSplitArrPID[i]);

                    //check PID is Extras or NOT
                        var chkPID = (from p in db.PlanNamesDetails where p.PlanNamesDetailID == PID select p.PlanNamesDetailID).FirstOrDefault();
                        if (chkPID > 0) //Plan Name Detail
                        {
                            //for each loop for Quota Price 
                            for (int j = 0; j < strSplitArrrelID.Length; j++)
                            {
                                if (strSplitArrType[j] == "configoptions" && GID == Convert.ToInt32(strSplitArrrelID[j]))
                                {
                                    //Insert into PlanQuota
                                    //Run all the If conditions:
                                    //monthly
                                    decimal ArrM = Convert.ToDecimal(strSplitArrM[j]);
                                    decimal ArrQ = Convert.ToDecimal(strSplitArrQ[j]);
                                    decimal ArrS = Convert.ToDecimal(strSplitArrS[j]);

                                    Int32 getGIDbyPID = 0;
                                    //get the GroupId of ProductID
                                    for (int l = 0; l < strSplitArrGPID.Length; l++)
                                    {
                                        if (!String.IsNullOrEmpty(strSplitArrGPID[l]))
                                        {
                                            if (PID == Convert.ToInt32(strSplitArrGPID[l]))
                                            {
                                                getGIDbyPID = Convert.ToInt32(strSplitArrGGID[l]);
                                            }
                                        }
                                    }

                                    if (ArrM > 0)
                                    {
                                        //check if same value already exists in the database.
                                        Int32 Qmonth = (int)QuotaMonths.OneMonth;
                                        String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                        Decimal ArrMy= Convert.ToDecimal(strSplitArrM[j]);
                                        Int32 GIDbyPID=  Convert.ToInt32(getGIDbyPID);

                                        var chkExitsAlready = (from p in db.PlanQuotas where p.PlanQuotaValue == Qmonth && p.PlanQuotaInterval == QmonthName && p.SetupCost == ArrMy && p.PlanNamesID == GIDbyPID select p.PlanQuotaID).FirstOrDefault();
                                        //means Value not exists in the database
                                        if (chkExitsAlready == 0)
                                        {
                                            PlanQuota modelM = new PlanQuota();
                                            modelM.PlanQuotaValue = Qmonth;
                                            modelM.PlanQuotaInterval = QmonthName;
                                            modelM.SetupCost = ArrMy;
                                            modelM.PlanNamesID = GIDbyPID;
                                            db.AddToPlanQuotas(modelM);
                                            db.SaveChanges();
                                        }
                                    }
                                    //quateraly
                                    if (ArrQ > 0)
                                    {
                                         //check if same value already exists in the database.
                                        Int32 Qmonth = (int)QuotaMonths.ThreeMonth;
                                        String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                        Decimal ArrMy = Convert.ToDecimal(strSplitArrQ[j]);
                                        Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                        var chkExitsAlready = (from p in db.PlanQuotas where p.PlanQuotaValue == Qmonth && p.PlanQuotaInterval == QmonthName && p.SetupCost == ArrMy && p.PlanNamesID == GIDbyPID select p.PlanQuotaID).FirstOrDefault();
                                        //means Value not exists in the database
                                        if (chkExitsAlready == 0)
                                        {

                                            PlanQuota modelQ = new PlanQuota();
                                            modelQ.PlanQuotaValue = Qmonth;
                                            modelQ.PlanQuotaInterval = QmonthName;
                                            modelQ.SetupCost = ArrMy;
                                            modelQ.PlanNamesID = GIDbyPID;
                                            db.AddToPlanQuotas(modelQ);
                                            db.SaveChanges();
                                        }
                                    }
                                    //semifinally
                                    if (ArrS > 0)
                                    {
                                        //check if same value already exists in the database.
                                        Int32 Qmonth = (int)QuotaMonths.SubYearly;
                                        String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                        Decimal ArrMy = Convert.ToDecimal(strSplitArrS[j]);
                                        Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                        var chkExitsAlready = (from p in db.PlanQuotas where p.PlanQuotaValue == Qmonth && p.PlanQuotaInterval == QmonthName && p.SetupCost == ArrMy && p.PlanNamesID == GIDbyPID select p.PlanQuotaID).FirstOrDefault();
                                        //means Value not exists in the database
                                        if (chkExitsAlready == 0)
                                        {

                                            PlanQuota modelS = new PlanQuota();
                                            modelS.PlanQuotaValue = Qmonth;
                                            modelS.PlanQuotaInterval = QmonthName;
                                            modelS.SetupCost = ArrMy;
                                            modelS.PlanNamesID = GIDbyPID;
                                            db.AddToPlanQuotas(modelS);
                                            db.SaveChanges();
                                        }
                                    }
                                }

                            }
                        }
                        else //Extras
                        {
                            var chkExitsD = (from p in db.SubExtrasDetails where p.SubExtrasDetailID == PID select p.SubExtrasDetailID).FirstOrDefault();
                            if (chkExitsD > 0) //Plan Name Detail
                            {
                                //for each loop for Quota Price 
                                for (int j = 0; j < strSplitArrrelID.Length; j++)
                                {
                                    if (strSplitArrType[j] == "configoptions" && GID == Convert.ToInt32(strSplitArrrelID[j]))
                                    {
                                        //Insert into PlanQuota
                                        //Run all the If conditions:
                                        //monthly
                                        decimal ArrM = Convert.ToDecimal(strSplitArrM[j]);
                                        decimal ArrQ = Convert.ToDecimal(strSplitArrQ[j]);
                                        decimal ArrS = Convert.ToDecimal(strSplitArrS[j]);

                                        Int32 getGIDbyPID = 0;
                                        //get the GroupId of ProductID
                                        for (int l = 0; l < strSplitArrGPID.Length; l++)
                                        {
                                            if (!String.IsNullOrEmpty(strSplitArrGPID[l]))
                                            {
                                                if (PID == Convert.ToInt32(strSplitArrGPID[l]))
                                                {
                                                    getGIDbyPID = Convert.ToInt32(strSplitArrGGID[l]);
                                                }
                                            }
                                        }

                                        if (ArrM > 0)
                                        {
                                            //check if same value already exists in the database.
                                            Int32 Qmonth = (int)QuotaMonths.OneMonth;
                                            String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                            Decimal ArrMy = Convert.ToDecimal(strSplitArrM[j]);
                                            Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                            var chkExitsAlready = (from p in db.ExtraPlanQuotas where p.ExtraPlanQuotaValue == Qmonth && p.ExtraPlanQuotaInterval == QmonthName && p.ExtraSetupCost == ArrMy && p.SubExtrasID == GIDbyPID select p.ExtraPlanQuotaID).FirstOrDefault();
                                            //means Value not exists in the database
                                            if (chkExitsAlready == 0)
                                            {
                                                ExtraPlanQuota modelM = new ExtraPlanQuota();
                                                modelM.ExtraPlanQuotaValue = Qmonth;
                                                modelM.ExtraPlanQuotaInterval = QmonthName;
                                                modelM.ExtraSetupCost = ArrMy;
                                                modelM.SubExtrasID = GIDbyPID;
                                                db.AddToExtraPlanQuotas(modelM);
                                                db.SaveChanges();
                                            }
                                        }
                                        //quateraly
                                        if (ArrQ > 0)
                                        {
                                             //check if same value already exists in the database.
                                            Int32 Qmonth = (int)QuotaMonths.ThreeMonth;
                                            String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                            Decimal ArrMy = Convert.ToDecimal(strSplitArrQ[j]);
                                            Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                            var chkExitsAlready = (from p in db.ExtraPlanQuotas where p.ExtraPlanQuotaValue == Qmonth && p.ExtraPlanQuotaInterval == QmonthName && p.ExtraSetupCost == ArrMy && p.SubExtrasID == GIDbyPID select p.ExtraPlanQuotaID).FirstOrDefault();
                                            //means Value not exists in the database
                                            if (chkExitsAlready == 0)
                                            {

                                                ExtraPlanQuota modelQ = new ExtraPlanQuota();
                                                modelQ.ExtraPlanQuotaValue = Qmonth;
                                                modelQ.ExtraPlanQuotaInterval = QmonthName;
                                                modelQ.ExtraSetupCost = ArrMy;
                                                modelQ.SubExtrasID = GIDbyPID;
                                                db.AddToExtraPlanQuotas(modelQ);
                                                db.SaveChanges();
                                            }
                                        }
                                        //semifinally
                                        if (ArrS > 0)
                                        {
                                            //check if same value already exists in the database.
                                            Int32 Qmonth = (int)QuotaMonths.SubYearly;
                                            String QmonthName = Convert.ToString(QuotaMonthYear.months);
                                            Decimal ArrMy = Convert.ToDecimal(strSplitArrS[j]);
                                            Int32 GIDbyPID = Convert.ToInt32(getGIDbyPID);

                                            var chkExitsAlready = (from p in db.ExtraPlanQuotas where p.ExtraPlanQuotaValue == Qmonth && p.ExtraPlanQuotaInterval == QmonthName && p.ExtraSetupCost == ArrMy && p.SubExtrasID == GIDbyPID select p.ExtraPlanQuotaID).FirstOrDefault();
                                            //means Value not exists in the database
                                            if (chkExitsAlready == 0)
                                            {
                                                ExtraPlanQuota modelS = new ExtraPlanQuota();
                                                modelS.ExtraPlanQuotaValue = Qmonth;
                                                modelS.ExtraPlanQuotaInterval = QmonthName;
                                                modelS.ExtraSetupCost = ArrMy;
                                                modelS.SubExtrasID = GIDbyPID;
                                                db.AddToExtraPlanQuotas(modelS);
                                                db.SaveChanges();
                                            }
                                        }
                                    }

                                }
                            }
                        }


                   
                    }


            }
            #endregion
            return View();
           }*/
            //Insert values into Quota Tables:

            //            //check Is PlanQuota alreay exists
            //            var chkExits = (from p in db.PlanNamesDetails where p.PlanNamesDetailID == planNDID select p.PlanNamesDetailID).FirstOrDefault();
            //            if (chkExits > 0) //Update Values in PlanNamesDetail
            //            {
            //                //update price in PlanNamesDetail table in the database.
            //                PlanNamesDetail dbPlanNamesDetail = new PlanNamesDetail { PlanNamesDetailID = chkExits };
            //                db.PlanNamesDetails.Attach(dbPlanNamesDetail);
            //                dbPlanNamesDetail.Price = Convert.ToDecimal(strSplitArrMonthly[i]);
            //                db.SaveChanges();
            //            }
            //            else //Update Values in SubExtrasDetails
            //            {
            //                Int32 planNDI = Convert.ToInt32(strSplitArrRelID[i]);
            //                var chkExitsD = (from p in db.SubExtrasDetails where p.SubExtrasDetailID == planNDI select p.SubExtrasDetailID).FirstOrDefault();
            //                if (chkExitsD > 0)
            //                {
            //                    //update price in the database.
            //                    SubExtrasDetail dbSubExtrasDetails = new SubExtrasDetail { SubExtrasDetailID = chkExitsD };
            //                    db.SubExtrasDetails.Attach(dbSubExtrasDetails);
            //                    dbSubExtrasDetails.SubExtrasDetailPrice = Convert.ToDecimal(strSplitArrMonthly[i]);
            //                    db.SaveChanges();
            //                }

            //            }

           //get Data from the XMl and save into the database.
           /* XmlDocument doc = new XmlDocument();
            doc.LoadXml(getXML);
            XmlElement root = doc.DocumentElement;
            //XmlNodeList nodes = root.SelectNodes("/whmcsapi/products"); // You can filter elements
            XmlNodeList nodes = root.GetElementsByTagName("products");
            //here using XPath
            foreach (XmlNode node in nodes)
            {
            string id = node["id"].InnerText;
            string name = node["name"].InnerText;
            }*/
           
           
            /*formcustom.Add("pid", "1");
            //formcustom.Add("action", "getproductconfigurations");*/
            /* formcustom.Add("id", "6");
            formcustom.Add("name", "SampleGroup");
            formcustom.Add("order", "6");
            formcustom.Add("disabledgateways", "");
            formcustom.Add("hidden", "on");
            formcustom.Add("action", "productgroup");// action performed by the API:Functions*/


            /*MySqlConnection con = new MySqlConnection();
            con.ConnectionString = "Data Source=localhost;Database= everynet;User ID=everynet;Password=everynet";
            con.Open();
            MySqlDataAdapter dr = new MySqlDataAdapter("Insert Into tblproductgroups(name,disabledgateways,hidden,order) values ('test','','on',5)", con);
            DataSet ds = new DataSet();
            dr.Fill(ds);*/


            /*string connetionString = null;
            //MySqlConnection connection;
            //MySqlDataAdapter adapter = new MySqlDataAdapter();
            //string sql = null;
            //connetionString = "Data Source=localhost;Database= everynet;User ID=everynet;Password=everynet";
            //connection = new MySqlConnection(connetionString);
            //sql = "Insert Into tblproductgroups values (5,'test','','on',5)";
            //try
            //{
            //    connection.Open();
            //    adapter.InsertCommand = new MySqlCommand(sql, connection);
            //    adapter.InsertCommand.ExecuteNonQuery();
            //}
            //catch (Exception ex)
            //{
                
            }*/
        
        
        //#region [Static Working]
        //public ActionResult WhmcsAPI()
        //{
        //    string username = "admin";
        //    string password = "21232f297a57a5a743894a0e4a801fc3";

        //    string path = "http://localhost:9080/whmcs/includes/api.php";

        //     // Instantiate the WebClient object
        //     WebClient WHMCSclient = new WebClient();

        //     // Prepare a Name/Value collection to hold the post values
        //     NameValueCollection form = new NameValueCollection();
        //     form.Add("username", username);
        //     form.Add("password", password); // the password will still need encoding is MD5 is a requirement

        //     form.Add("action", "addclient");// action performed by the API:Functions

        //     form.Add("firstname", "TestSahil");
        //     form.Add("lastname", "TestSahillast");
        //     form.Add("companyname", "TestSahil");
        //     form.Add("email", "sahilk4@nascenture.com");
        //     form.Add("address1", "Test Address");
        //     form.Add("city", "Test City");
        //     form.Add("state", "Test State");
        //     form.Add("postcode", "Test 123");
        //     form.Add("country", "INDIA");
        //     form.Add("phonenumber", "1234567");
        //     form.Add("password2", "admin");
        //     form.Add("currency", "3");

        //    // Post the data and read the response
        //     Byte[] responseData = WHMCSclient.UploadValues(path, form);

        //    // Decode and display the response.
        //    ViewBag.DisplayData = Encoding.ASCII.GetString(responseData);
        //    return View();
        //}
        //#endregion

        public static string Mainusername = ConfigurationManager.AppSettings["WhmcsUsername"].ToString();
        public static string Mainpassword = ConfigurationManager.AppSettings["WhmcsPassword"].ToString();
        public static string path = ConfigurationManager.AppSettings["WhmcsPath"].ToString();
       
        public ActionResult WhmcsTest()
        {
            Int64 userID = 2;
            // Instantiate the WebClient object
            WebClient WHMCSclient = new WebClient();
            #region [Get UserData from Sql Database with UserID]
            //Get Data from Sql Database with UserID
            var model = new signUpModel();
            model = (from U in db.Users
                     where U.ID == userID
                     select new signUpModel()
                     {
                         FirstName = U.FirstName,
                         LastName = U.LastName,
                         MobileNumber = U.MobileNumber,
                         Email = U.Email,
                         ServiceAddress = U.ServiceAddress,
                         ServicePhoneNumber = U.ServicePhoneNumber,
                         Password = U.Password,
                         RegisterDateTime = U.RegisterDateTime,
                         IPAddress = U.IPAddress
                     }).SingleOrDefault();
            #endregion

            #region[Save Data to Client Table]
            // Prepare a Name/Value collection to hold the post values
            NameValueCollection form = new NameValueCollection();
            form.Add("username", Mainusername);
            form.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement


            form.Add("action", "addclient");// action performed by the API:Functions

            form.Add("firstname", model.FirstName);
            form.Add("lastname", model.LastName);
            form.Add("companyname", "");
            form.Add("email", model.Email);
            form.Add("address1", model.ServiceAddress);
            form.Add("customfield[1]", model.ServicePhoneNumber.ToString()); //Service Phone Number
            form.Add("city", "");
            form.Add("state", "");
            form.Add("postcode", "");
            form.Add("country", "");
            form.Add("phonenumber", model.MobileNumber.ToString());
            form.Add("password2", model.Password);
            form.Add("datecreated", model.RegisterDateTime.ToString());
            form.Add("ip", model.IPAddress);
            form.Add("currency", "");
            form.Add("skipvalidation", 1.ToString());


            Byte[] responseData = WHMCSclient.UploadValues(path, form);

            string getCustomerIDfromWHMCS = string.Empty;
            string splitFullString = Encoding.ASCII.GetString(responseData);
            if (!String.IsNullOrEmpty(splitFullString))
            {
                string[] splitwords = splitFullString.Split(';');
                string[] subsplitwords = splitwords[1].Split('=');
                getCustomerIDfromWHMCS = subsplitwords[1];
            }
            #endregion
            #region[Save Data to Contact Table]
            if (!String.IsNullOrEmpty(getCustomerIDfromWHMCS))
            {

                NameValueCollection formContact = new NameValueCollection();
                formContact.Add("username", Mainusername);
                formContact.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
                formContact.Add("action", "addcontact");// action performed by the API:Functions

                formContact.Add("clientid", getCustomerIDfromWHMCS); //Current Id of the user that is Inserted in WHMCS.
                formContact.Add("firstname", model.FirstName);
                formContact.Add("lastname", model.LastName);
                formContact.Add("email", model.Email);
                formContact.Add("address1", model.ServiceAddress);
                formContact.Add("phonenumber", model.MobileNumber.ToString());
                formContact.Add("password2", model.Password);

                Byte[] responseDataContact = WHMCSclient.UploadValues(path, formContact);
            }
            #endregion

            //#region[Get Data from Sql Database with UserID]
            // var resultOrder = (db.GetTotalPricebyClientID(userID)).SingleOrDefault();
            //#endregion
            #region[Save Data to Order Table]

            if (!String.IsNullOrEmpty(getCustomerIDfromWHMCS))
            {
                NameValueCollection formOrder = new NameValueCollection();
                formOrder.Add("username", Mainusername);
                formOrder.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement

                formOrder.Add("action", "addorder");// action performed by the API:Functions
                formOrder.Add("clientid", getCustomerIDfromWHMCS);
                formOrder.Add("paymentmethod", "paypal");
                
                //to get the products attach with the User ID
                //Get the product ids in comma separated String.(Main Product ID concatenate with Extras IDS)
                //Main Product
                String getMainProductValue = Convert.ToString((from e in db.Users where e.ID == userID select e.PlanNamesDetailID).SingleOrDefault());
                Int32? getplanQuotaID = (from e in db.Users where e.ID == userID select e.PlanQuotaID).SingleOrDefault();
                String getMainPlanQuotaValue = Convert.ToString((from e in db.PlanQuotas where e.PlanQuotaID == getplanQuotaID select e.PlanQuotaValue).SingleOrDefault()); ;
               
                //Get Quota in List
                List<SubExtrasDetail> lstQuota = new List<SubExtrasDetail>();
                lstQuota = (from EPQU in db.ExtraPlanQuotaAssigntoUsers
                                          join EPQ in db.ExtraPlanQuotas on EPQU.ExtraPlanQuotaID equals EPQ.ExtraPlanQuotaID
                                          where
                                            EPQU.UserID == userID
                                           select new SubExtrasDetail()
                                          {
                                              SubExtrasDetailID = (Int32)EPQU.SubExtrasDetailID,
                                              ExtraPlanQuotaValue = EPQ.ExtraPlanQuotaValue
                                          }).ToList();
                
                //Get Extras in List
                List<SubExtrasDetail> lst = new List<SubExtrasDetail>();
                lst = (from e in db.SubExtrasDetailAssignToUsers
                       where e.UserID == userID
                       orderby e.SubExtrasDetailID
                       select new SubExtrasDetail() { SubExtrasDetailID = e.SubExtrasDetailID }).ToList();
                //Foreach Extras
                foreach (var item in lst)
                {
                    getMainProductValue += "," + item.SubExtrasDetailID;
                    //Foreach Quotas
                    foreach (var itemQ in lstQuota)
                    {
                        if (itemQ.SubExtrasDetailID == item.SubExtrasDetailID)
                        {
                            getMainPlanQuotaValue += "," + itemQ.ExtraPlanQuotaValue;
                        }
                    }

                }

                var primeArray = getMainProductValue.Split(',');
                var primeArrayQuota = getMainPlanQuotaValue.Split(',');

                List<string[]> arrays = new List<string[]>();
                for (int i = 0; i < primeArray.Length; i++)
                {
                    var first = primeArray[i];
                    var Quota =Convert.ToInt32(primeArrayQuota[i]);
                    formOrder.Add("pid["+(i + 1)+"]", first.ToString());
                    int value = Quota;
                    switch (value)
                    {
                        case 1:
                            formOrder.Add("billingcycle[" + (i + 1) + "]", "monthly");
                            break;
                        case 3:
                            formOrder.Add("billingcycle[" + (i + 1) + "]", "quarterly");
                            break;
                        case 6:
                            formOrder.Add("billingcycle[" + (i + 1) + "]", "semiannually");
                            break;
                        case 12:
                            formOrder.Add("billingcycle[" + (i + 1) + "]", "annually");
                            break;
                        case 24:
                            formOrder.Add("billingcycle[" + (i + 1) + "]", "biennially");
                            break;
                        case 36:
                            formOrder.Add("billingcycle[" + (i + 1) + "]", "triennially");
                            break;
                        default:
                            formOrder.Add("billingcycle[" + (i + 1) + "]", "monthly");
                            break;

                    }

                }
                Byte[] responseDataOrder = WHMCSclient.UploadValues(path, formOrder);
                //formOrder.Add("regperiod", "3");
                //onetime, monthly, quarterly, semiannually,annually,biennially,triennially etc..
                /*formOrder.Add("pid[1]", "1");
                formOrder.Add("pid[2]", "2");*/


                //formOrder.Add("pid[1]", "23");
                //formOrder.Add("pid[2]", "29");
                //formOrder.Add("pid[3]", "30");
               
                /*formOrder.Add("regperiod", "1");
                formOrder.Add("billingcycle[1]", "monthly");
                formOrder.Add("billingcycle[2]", "monthly");*/
               /* formOrder.Add("billingcycle[3]", "monthly");*/
               /* formOrder.Add("pid[1]", "23");
                 formOrder.Add("billingcycle[1]", "monthly");*/
               
            }
            #endregion
           return View();
        }

        public class SubExtrasDetail
        {
            public Int32 SubExtrasDetailID { get; set; }
            public Int32 ExtraPlanQuotaValue { get; set; }
            // Other field you may need from the Product entity
        }
        
        /*public ActionResult WhmcsTest()
        {
            // Instantiate the WebClient object
            WebClient WHMCSclient = new WebClient();

            #region [Get UserData from Sql Database with UserID]
            var model = new signUpModel();
            model = (from U in db.Users
                     where U.ID == 42
                     select new signUpModel()
                     {
                         ID = U.ID,
                         //Title=U.Title,    
                         FirstName = U.FirstName,
                         LastName = U.LastName,
                         MobileNumber = U.MobileNumber,
                         Email = U.Email,
                         ServiceAddress = U.ServiceAddress,
                         ServicePhoneNumber = U.ServicePhoneNumber,
                         //UserName=U.UserName,                                           
                         Password = U.Password,
                         RegisterDateTime = U.RegisterDateTime,
                         IPAddress = U.IPAddress
                     }).SingleOrDefault();
            #endregion
            // Prepare a Name/Value collection to hold the post values
            #region[Save Data to Client Table]
            NameValueCollection form = new NameValueCollection();
            form.Add("username", Mainusername);
            form.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
            form.Add("action", "addclient");// action performed by the API:Functions

            form.Add("firstname", model.FirstName);
            form.Add("lastname", model.LastName);
            form.Add("companyname", "");
            form.Add("email", model.Email);
            form.Add("address1", model.ServiceAddress);
            form.Add("customfield[1]", model.ServicePhoneNumber.ToString()); //Service Phone Number
            form.Add("city", "");
            form.Add("state", "");
            form.Add("postcode", "");
            form.Add("country", "");
            form.Add("phonenumber", model.MobileNumber.ToString());
            form.Add("password2", model.Password);
            form.Add("datecreated", model.RegisterDateTime.ToString());
            form.Add("ip", model.IPAddress);
            form.Add("currency", "");
            form.Add("skipvalidation", 1.ToString());

            //Byte[] responseData = WHMCSclient.UploadValues(path, form);
            //ViewBag.DisplayData = Encoding.ASCII.GetString(responseData);
            //string getCustomerIDfromWHMCS = string.Empty;
            //string splitFullString = Encoding.ASCII.GetString(responseData);
            //if (!String.IsNullOrEmpty(splitFullString))
            //{
            //    string[] splitwords = splitFullString.Split(';');
            //    string[] subsplitwords = splitwords[1].Split('=');
            //    getCustomerIDfromWHMCS = subsplitwords[1];
            //}

            #region [Other fields use later]
            //form.Add("firstname", "TestSahil");
            //form.Add("lastname", "TestSahillast");
            //form.Add("companyname", "TestSahil");
            //form.Add("email", "sahilk7@nascenture.com");
            //form.Add("address1", "Test Address");
            //form.Add("city", "Test City");
            //form.Add("state", "Test State");
            //form.Add("postcode", "Test 123");
            //form.Add("country", "INDIA");
            //form.Add("phonenumber", "1234567");
            //form.Add("password2", "admin");
            //form.Add("currency", "3");
            //form.Add("address2", "");
            //form.Add("id", "");
            //form.Add("companyname", "");
            //form.Add("city", "");
            //form.Add("state", "");
            //form.Add("postcode", "");
            //form.Add("country", "");
            //form.Add("currency", "");
            //form.Add("defaultgateway", "");
            //form.Add("credit", "");
            //form.Add("taxexempt", "");
            //form.Add("latefeeoverride", "");
            //form.Add("overidduenotices", "");
            //form.Add("separateinvoices", "");
            //form.Add("disableautocc", "");
            //form.Add("notes", "");
            //form.Add("billingcid", "");
            //form.Add("securityqid", "");
            //form.Add("securityqans", "");
            //form.Add("groupid", "");
            //form.Add("cardtype", "");
            //form.Add("cardlastfour", "");
            //form.Add("cardnum", "");
            //form.Add("startdate", "");
            //form.Add("expdate", "");
            //form.Add("issuenumber", "");
            //form.Add("bankname", "");
            //form.Add("banktype", "");
            //form.Add("bankcode", "");
            //form.Add("bankacct", "");
            //form.Add("gatewayid", "");
            //form.Add("lastlogin", "");
            //form.Add("host", "");
            //form.Add("status", "");
            //form.Add("language", "");
            //form.Add("pwresetkey", "");
            //form.Add("pwresetexpiry", "");
            #endregion
            #endregion
            #region[Save Data to Contact Table]
            //if (!String.IsNullOrEmpty(getCustomerIDfromWHMCS))
            //{
            NameValueCollection formContact = new NameValueCollection();
            formContact.Add("username", Mainusername);
            formContact.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement
            formContact.Add("action", "addcontact");// action performed by the API:Functions

            //formContact.Add("clientid", getCustomerIDfromWHMCS);
            formContact.Add("clientid", 6.ToString());

            formContact.Add("firstname", model.FirstName);
            formContact.Add("lastname", model.LastName);
            formContact.Add("email", model.Email);
            formContact.Add("address1", model.ServiceAddress);
            formContact.Add("phonenumber", model.MobileNumber.ToString());
            formContact.Add("password2", model.Password);

            //Byte[] responseDataContact = WHMCSclient.UploadValues(path, formContact);
            //ViewBag.DisplayData = Encoding.ASCII.GetString(responseDataContact);

            #region[other fields ofcontact Use Later]
            //formContact.Add("companyname", "");
            //formContact.Add("subaccount", "");
            //formContact.Add("address2", "");
            //formContact.Add("city", "");
            //formContact.Add("state", "");
            //formContact.Add("postcode", "");
            //formContact.Add("country", "");
            //formContact.Add("permissions", "");
            //formContact.Add("domainemails", "");
            //formContact.Add("generalemails", "");
            //formContact.Add("invoiceemails", "");
            //formContact.Add("productemails", "");
            //formContact.Add("supportemails", "");
            //formContact.Add("pwresetkey", "");
            //formContact.Add("pwresetexpiry", "");
            #endregion
            //}
            #endregion

            #region[Get Data from Sql Database with UserID]
            var resultOrder = (db.GetTotalPricebyClientID(45)).SingleOrDefault();
            #endregion
            #region[Save Data to Order Table (Product/Services)]

            #region [multiple Values of product]
            //            $postfields["action"] = "addorder";
            //            $postfields["clientid"] = "1";

            //            $postfields["pid[0]"] = "1";
            //            $postfields["domain[0]"] = "whmcs.com";
            //            $postfields["billingcycle[0]"] = "monthly";

            //            $postfields["pid[1]"] = "1";
            //            $postfields["domain[1]"] = "whmcs2.com";
            //            $postfields["billingcycle[1]"] = "monthly";

            //            $postfields["pid[2]"] = "5";
            //            $postfields["domain[2]"] = "whmcs3.com";
            //            $postfields["billingcycle[2]"] = "annually";

            //            $postfields["noemail"] = "true";
            //            $postfields["paymentmethod"] = "authorize";
            #endregion

            //if (!String.IsNullOrEmpty(getCustomerIDfromWHMCS))
            //{
            NameValueCollection formOrder = new NameValueCollection();
            formOrder.Add("username", Mainusername);
            formOrder.Add("password", Mainpassword); // the password will still need encoding is MD5 is a requirement

            formOrder.Add("action", "addorder");// action performed by the API:Functions

            formOrder.Add("clientid", 6.ToString());

            formOrder.Add("clientip", resultOrder.IPAddress);
            formOrder.Add("paymentmethod", "paypal");

            formOrder.Add("pid[1]", "1");
            formOrder.Add("pid[2]", "2");

            formOrder.Add("regperiod", "1");
            formOrder.Add("billingcycle[1]", "monthly");
            formOrder.Add("billingcycle[2]", "monthly");

            //formOrder.Add("clientid", getCustomerIDfromWHMCS);
            //formOrder.Add("date", resultOrder.RegisterDateTime.ToString());
            //formOrder.Add("priceoverride", resultOrder.TotalCost.ToString());
            //formOrder.Add("status", resultOrder.OrderStatus.ToString());

            // Byte[] responseDataOrder = WHMCSclient.UploadValues(path, formOrder);
            // Decode and display the response.
            //ViewBag.DisplayData = Encoding.ASCII.GetString(responseDataOrder);

            #region[static Order values]
            //formOrder.Add("clientid", 1.ToString());
            //formOrder.Add("pid", 1.ToString());
            //formOrder.Add("domain", "whmcs.com");
            //formOrder.Add("billingcycle", "monthly");
            //formOrder.Add("addons", "1");

            //formOrder.Add("domaintype", "register");
            //formOrder.Add("regperiod", "1");
            //formOrder.Add("paymentmethod", "paypal");
            #endregion
            #region [Other Fields of Orders Use Later]
            ////formOrder.Add("contactid", "");
            ////formOrder.Add("id", "");
            ////formOrder.Add("ordernum", "");
            ////formOrder.Add("nameservers", "");
            ////formOrder.Add("transfersecret", "");
            ////formOrder.Add("renewals", "");
            ////formOrder.Add("promocode", "");
            ////formOrder.Add("promotype", "");
            ////formOrder.Add("promovalue", "");
            ////formOrder.Add("orderdata", "");
            ////formOrder.Add("paymentmethod", "");
            ////formOrder.Add("invoiceid", "");
            ////formOrder.Add("fraudmodule", "");
            ////formOrder.Add("fraudoutput", "");
            ////formOrder.Add("notes", "");
            #endregion
            //}
            #endregion

            #region Add Products in Database
            NameValueCollection formProducts = new NameValueCollection();
            formProducts.Add("username", Mainusername);
            formProducts.Add("password", Mainpassword);
            formProducts.Add("action", "addproduct");// action performed by the API:Functions
            formProducts.Add("type", "other");
            formProducts.Add("gid", "1");
            formProducts.Add("name", "Sample Product1");
            formProducts.Add("paytype", "recurring");

            formProducts.Add("pricing[1][monthly]", "50.00");
            formProducts.Add("pricing[1][annually]", "50.00");

            //formProducts.Add("pricing[2][monthly]", "8.00");
            //formProducts.Add("pricing[2][annually]", "80.00");

            //Byte[] responseDataOrder = WHMCSclient.UploadValues(path, formProducts);
            // Decode and display the response.
            //ViewBag.DisplayData = Encoding.ASCII.GetString(responseDataOrder);
            #endregion

            return View();
        }*/
        #endregion
      /*  #region [Testing Service Qualification API]
        public string serviceLocal()
        {
            string firstxml = @"<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
                                           xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" 
                                           xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
                                          <soap:Body>
                                          <AdddressBased xmlns=""http://tempuri.org/"">
                                          <Address>abc</Address>
                                          </AdddressBased>
                                          </soap:Body>
                                          </soap:Envelope>";
            string soapaction = "http://tempuri.org/AdddressBased";
            string url1 = "http://everynet.nascenture.com/checkdata.asmx";

            return serviceLocalExecute(firstxml, soapaction, url1);
        }
        public string serviceLocalExecute(string xml, string soapaction, string url1)
        {

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url1);
            webRequest.Headers.Add("SOAPAction", soapaction);
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Accept = "text/xml";
            webRequest.Method = "POST";

            XmlDocument soapEnvelopeXml = new XmlDocument();

            soapEnvelopeXml.LoadXml(xml);

            using (Stream stream = webRequest.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }

            using (WebResponse response = webRequest.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    string soapResult = rd.ReadToEnd();
                    return soapResult;
                }
            }
        }
        public string GetFaultMessage(XmlDocument xd)
        {
            #region [Get Fault specific Value]
            XmlNamespaceManager managerFault = new XmlNamespaceManager(xd.NameTable);
            managerFault.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
            managerFault.AddNamespace("ns2", "http://www.vocus.net.au/Wholesale/Schemas/External/1.0/DSL/Provisioning");
            string queryFault = "/soap:Envelope/soap:Body/soap:Fault/detail/ns2:ServiceFault/faultDescription";
            string getBodyXMLFault = string.Empty;
            XmlNodeList xnListFault = xd.SelectNodes(queryFault, managerFault);
            foreach (XmlNode xnFault in xnListFault)
            {
                getBodyXMLFault = xnFault.InnerText;
            }
            return getBodyXMLFault;
            #endregion
        }
        public Int32 GetSuccessMessage(XmlDocument xd)
        {
            #region [Get Specific Node Value]
            Int32 returnSuccess = 0;

            XmlNamespaceManager manager = new XmlNamespaceManager(xd.NameTable);
            manager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
            manager.AddNamespace("ns2", "http://www.vocus.net.au/Wholesale/Schemas/External/1.0/DSL/Provisioning/ServiceQualification.xsd");
            string query = "/soap:Envelope/soap:Body/ns2:ServiceQualificationResponse/StatusDescription";

            string getBodyXML = string.Empty;
            string getNetXML = string.Empty;
            string getNetAlready = string.Empty;
            string getOffNetZone = string.Empty;
            string getOnNetPass = string.Empty;
            string getOffNetZonePass = string.Empty;
            Int32 selectedPlan = 0;

            XmlNodeList xnList = xd.SelectNodes(query, manager);
            foreach (XmlNode xn in xnList)
            {
                getBodyXML = xn.InnerText;
            }

            if (getBodyXML == "Completed")
            {
                //check it is net(OnNet/OffNet)
                string queryNet = "/soap:Envelope/soap:Body/ns2:ServiceQualificationResponse/Net";
                XmlNodeList xnListNet = xd.SelectNodes(queryNet, manager);
                foreach (XmlNode xnNet in xnListNet)
                {
                    getNetXML = xnNet.InnerText;
                }

                //check DSL Already exist on this Line:
                string queryAlready = "/soap:Envelope/soap:Body/ns2:ServiceQualificationResponse/DSLFound";
                XmlNodeList xnListAlready = xd.SelectNodes(queryAlready, manager);
                foreach (XmlNode xnNetAlready in xnListAlready)
                {
                    getNetAlready = xnNetAlready.InnerText;
                }
                // getNetAlready

                //This is the Zone chart
                //OnNet                                     ||    Offnet
                //National ADSL 2 (No Zone required)        ||    National ADSL 2 (Zone1) 
                //                                          ||    Regional ADSL(Zone2,Zone3)

                //check the Zone of the line.
                //Zone is also in case of 'Offnet', class is only in case of 'OnNet'.

                //If Net is not null or blank
                if (!String.IsNullOrEmpty(getNetXML))
                {
                    //<Net>OffNet</Net>
                    //database ids --National ADSL2(3), Regional ADSL2(5)
                    if (getNetXML == "OffNet") //National ADSL 2 (Zone1), Regional ADSL(Zone 2,Zone 3)
                    {
                        string queryZone = "/soap:Envelope/soap:Body/ns2:ServiceQualificationResponse/Result/Zone";
                        XmlNodeList xnListZone = xd.SelectNodes(queryZone, manager);
                        foreach (XmlNode xnNetZone in xnListZone)
                        {
                            getOffNetZone = xnNetZone.InnerText;
                        }


                        string queryZonePass = "/soap:Envelope/soap:Body/ns2:ServiceQualificationResponse/Result/Pass";
                        XmlNodeList xnListZonePass = xd.SelectNodes(queryZonePass, manager);
                        foreach (XmlNode xnNetZonePass in xnListZonePass)
                        {
                            getOffNetZonePass = xnNetZonePass.InnerText;
                        }

                        if (Request.Cookies["cookieplanIdfixed"] != null) //--National ADSL2(3), Regional ADSL2(5)
                        {
                            selectedPlan = Convert.ToInt32(Request.Cookies["cookieplanIdfixed"].Value.ToString());

                            //<Zone>Zone 2</Zone>
                            if (((selectedPlan == 3) && (getOffNetZone == "Zone 1")) || ((selectedPlan == 5) && (getOffNetZone == "Zone 2" || getOffNetZone == "Zone 3")))
                            {
                                returnSuccess = 1;
                            }
                            if (((selectedPlan == 3) && (getOffNetZone == "Zone 1")) || ((selectedPlan == 5) && (getOffNetZone == "Zone 2" || getOffNetZone == "Zone 3")) && getNetAlready == "1")
                            {
                                returnSuccess = 2;
                            }
                        }

                    }
                    //database ids --National ADSL2(3)
                    else if (getNetXML == "OnNet") //National ADSL 2 (No Zone required)
                    {
                        string queryPass = "/soap:Envelope/soap:Body/ns2:ServiceQualificationResponse/Result/Pass";
                        XmlNodeList xnListPass = xd.SelectNodes(queryPass, manager);
                        foreach (XmlNode xnNetPass in xnListPass)
                        {
                            getOnNetPass = xnNetPass.InnerText;
                        }

                        if (Request.Cookies["cookieplanIdfixed"] != null) //--National ADSL2(3)
                        {
                            selectedPlan = Convert.ToInt32(Request.Cookies["cookieplanIdfixed"].Value.ToString());
                            if (getOnNetPass == "1" && selectedPlan == 3)       //<Pass>1</Pass>
                            {
                                returnSuccess = 1;
                            }
                            if (getOnNetPass == "1" && selectedPlan == 3 && getNetAlready == "1")     //<Pass>1</Pass><DSLFound>1</DSLFound>
                            {
                                returnSuccess = 2;
                            }
                        }
                    }
                }

                return returnSuccess;

            }
            else
            {
                //return "Unable to process.";
                return 0;

            }
            #endregion
        }
        public ActionResult ServiceTest()
        {
            //Basic concept use:
            //1.) if 0 means no service exists for it.
            //2.) if 1 means service exists for it.(dsl already not exists.)
            //3.) if 2 means service exists and also dsl is already exists.

            String getFinalResult = string.Empty;
            Int32 getFinalResutINT = 0; // if it is zero means Service not exist for it.if true service Exist.
            //OffNet: 0383609145
            //OnNet: 0296494901
            //UnabletoProcess: 0397946171
            //normal:0261004750
            string strServiceNumber = "0261004750";
            //Comment one at a time to see 2 cases:
            //string getXML= ErrorserviceStaging();//WORKING
            string getXML = serviceStaging(strServiceNumber); //WORKING
            try
            {
                XmlDocument xd = new XmlDocument();
                xd.LoadXml(getXML);
                string getXMLBeautify = Beautify(xd);

                if (getXML.Contains("<soap:Fault>"))
                {
                    #region [Get Fault specific Value]
                    // getFinalResult = GetFaultMessage(xd);
                    getFinalResutINT = 0;
                    #endregion
                }
                else if (getXML.Contains("SQ Response: Pass"))
                {
                    //getFinalResult = GetSuccessMessage(xd);
                    getFinalResutINT = GetSuccessMessage(xd);
                }


                //ViewBag.DisplayData = getFinalResult;
                ViewBag.DisplayData = getFinalResutINT;

            }
            catch
            {
                //ViewBag.DisplayData = getFinalResult;
                ViewBag.DisplayData = 0;
            }

            return View();
        }
        public string serviceStaging(string ServiceNumber)
        {
            string Urlpath = ConfigurationManager.AppSettings["ServiceQualificationAPIUrl"].ToString();
            string UrlAction = ConfigurationManager.AppSettings["ServiceQualificationAPIAction"].ToString();

            string getXml = @"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" 
                               xmlns:ser=""http://www.vocus.net.au/Wholesale/Schemas/External/1.0/DSL/Provisioning/ServiceQualification.xsd"">
                                  <soapenv:Header>
                                  <ser:SoapHeaderMsg>
                                     <ContextId>ServiceQualification-Success-01</ContextId>
                                  </ser:SoapHeaderMsg>
                               </soapenv:Header>                               
                                 <soapenv:Body>
                                  <ser:ServiceQualificationRequest>
                                     <FNN>" + ServiceNumber + @"</FNN>
                                  </ser:ServiceQualificationRequest>
                               </soapenv:Body>
                            </soapenv:Envelope>";
            return ExecuteCommon(getXml, UrlAction, Urlpath);
        }
        public string ExecuteCommon(string xml, string soapaction, string url1)
        {
            String certPath = Server.MapPath("~/cert/everynet.uat.p12");
            //Staging test with HTTPS:
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url1);

            webRequest.Headers.Add("SOAPAction", soapaction);
            webRequest.ContentType = "text/xml";
            webRequest.Method = "POST";

            //Certificate with private key
            X509Certificate2 cert = new X509Certificate2(certPath, "busty54AYe%");
            webRequest.ClientCertificates.Add(cert);
            webRequest.PreAuthenticate = true;


            XmlDocument soapEnvelopeXml = new XmlDocument();
            soapEnvelopeXml.LoadXml(xml);

            using (Stream stream = webRequest.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }
            string returnXML = String.Empty;

            try
            {
                using (var response = webRequest.GetResponse() as HttpWebResponse)
                {
                    if (webRequest.HaveResponse && response != null)
                    {
                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            string result = reader.ReadToEnd();
                            returnXML = result;
                        }
                    }

                }
            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)wex.Response)
                    {
                        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            string error = reader.ReadToEnd();
                            returnXML = error;
                        }
                    }
                }

            }
            return returnXML;

        }
        static public string Beautify(XmlDocument doc)
        {
            StringBuilder sb = new StringBuilder();
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = "  ";
            settings.NewLineChars = "\r\n";
            settings.NewLineHandling = NewLineHandling.Replace;
            using (XmlWriter writer = XmlWriter.Create(sb, settings))
            {
                doc.Save(writer);
            }
            return sb.ToString();
        }
        #region another code
        public string ErrorserviceStaging()
        {
            string Urlpath = ConfigurationManager.AppSettings["ServiceQualificationAPIUrl"].ToString();
            string UrlAction = ConfigurationManager.AppSettings["ServiceQualificationAPIAction"].ToString();

            string getXml = @"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:ser=""http://www.vocus.net.au/Wholesale/Schemas/External/1.0/DSL/Provisioning/ServiceQualification.xsd""><soapenv:Header><ser:SoapHeaderMsg><ContextId>ServiceQualification-Error-01</ContextId></ser:SoapHeaderMsg></soapenv:Header><soapenv:Body><ser:ServiceQualificationRequest><FNN>0261004750</FNN></ser:ServiceQualificationRequest></soapenv:Body></soapenv:Envelope>";
            return ExecuteCommon(getXml, UrlAction, Urlpath);
        }
        public string serviceLive()
        {
            string firstxml =
               @"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" 
               xmlns:ser=""http://www.vocus.net.au/Wholesale/Schemas/External/1.0/DSL/Provisioning/ServiceQualification.xsd""> 
           <soapenv:Header> 
               <ser:SoapHeaderMsg> 
                 <ContextId>ServiceQualification-Success-01</ContextId>
                   </ser:SoapHeaderMsg> 
           </soapenv:Header> 
           <soapenv:Body> 
                 <ser:ServiceQualificationRequest> 
                 <FNN>0289991234</FNN> 
                 </ser:ServiceQualificationRequest> 
           </soapenv:Body> 
          </soapenv:Envelope>";
            string soapaction = "https://b2b.vocus.com.au/services/ws/ProvisioningServiceSOAP/ServiceQualification"; //
            string url1 = "https://b2b.vocus.com.au/services/ws/ProvisioningServiceSOAP";

            return ExecuteCommon(firstxml, soapaction, url1);

        }

        //        public string  CallWebService()
        //        {
        //            //var _url = "http://everynet.nascenture.com/checkdata.asmx";
        //            //var _action = "http://tempuri.org/AdddressBased";

        //            string _action = "https://staging.b2b.vocus.com.au/services/ws/ProvisioningServiceSOAP/ServiceQualification";
        //            string _url = "https://staging.b2b.vocus.com.au/services/ws/ProvisioningServiceSOAP";

        //            XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
        //            HttpWebRequest webRequest = CreateWebRequest(_url, _action);

        //            X509Certificate2 cert = new X509Certificate2(@"E:\Projects\Everynet Project\Everynet\Everynet\everynet.uat.p12", "busty54AYe%");
        //            webRequest.ClientCertificates.Add(cert);
        //            webRequest.PreAuthenticate = true;

        //            InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);

        //            // begin async call to web request.
        //            IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

        //            // suspend this thread until call is complete. You might want to
        //            // do something usefull here like update your UI.
        //            asyncResult.AsyncWaitHandle.WaitOne();

        //            // get the response from the completed web request.
        //            string soapResult;

        //            try
        //            {
        //                using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))

        //                using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
        //                {
        //                    soapResult = rd.ReadToEnd();
        //                }
        //            }

        //            catch (WebException e)
        //            {
        //                string a = "This program is expected to throw WebException on successful run." + "\n\nException Message :" + e.Message;

        //                if (e.Status == WebExceptionStatus.ProtocolError)
        //                {
        //                    a += ((HttpWebResponse)e.Response).StatusCode.ToString() + " ";
        //                    a += ((HttpWebResponse)e.Response).StatusDescription.ToString() + " ";
        //                    a += ((HttpWebResponse)e.Response).ResponseUri.ToString()+ " ";
        //                    a += ((HttpWebResponse)e.Response).ProtocolVersion.ToString()+" ";
        //                    a += ((HttpWebResponse)e.Response).Server.ToString()+" ";
        //                    a += ((HttpWebResponse)e.Response).Headers.ToString();
        //                }

        //                return a;
        //            }
        //            return soapResult.ToString();



        //        }


        //        private static HttpWebRequest CreateWebRequest(string url, string action)
        //        {
        //            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        //            webRequest.Headers.Add("SOAPAction", action);
        //            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
        //            webRequest.Accept = "text/xml";
        //            webRequest.Method = "POST";
        //            return webRequest;
        //        }

        //        private static XmlDocument CreateSoapEnvelope()
        //        {
        //            XmlDocument soapEnvelop = new XmlDocument();

        //            soapEnvelop.LoadXml(
        //              @"<?xml version=""1.0"" encoding=""UTF-8"" ?><soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" 
        //               xmlns:ser=""http://www.vocus.net.au/Wholesale/Schemas/External/1.0/DSL/Provisioning/ServiceQualification.xsd""> 
        //           <soapenv:Header> 
        //               <ser:SoapHeaderMsg> 
        //                 <ContextId>ServiceQualification-Success-01</ContextId>
        //                   </ser:SoapHeaderMsg> 
        //           </soapenv:Header> 
        //           <soapenv:Body> 
        //                 <ser:ServiceQualificationRequest> 
        //                 <FNN>0289991234</FNN> 
        //                 </ser:ServiceQualificationRequest> 
        //           </soapenv:Body> 
        //          </soapenv:Envelope>");

        //            return soapEnvelop;
        //        }

        //        private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
        //        {
        //            using (Stream stream = webRequest.GetRequestStream())
        //            {
        //                soapEnvelopeXml.Save(stream);
        //            }
        //        }
        #endregion
        #endregion*/


      
    }
}